import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
import useSWR from 'swr';
import { getProject, Project } from '@/controller/project';
import { Loader2 } from 'lucide-react';

interface ProgressBarProps {
  title: string;
  onSearchCompleted: (flag: boolean, projectData: Project | null) => void;
  projectId: string;
}

export function ProgressBar({ title, onSearchCompleted, projectId }: ProgressBarProps) {
  const [progress, setProgress] = useState(0);
  const [isPolling, setIsPolling] = useState(true);

  const { data: projectData, error } = useSWR(
    isPolling ? `/api/project/${projectId}` : null,
    () => getProject(projectId),
    {
      refreshInterval: 3000  // 每3秒轮询一次
    }
  );

  const incrementProgress = () => {
    // 计算每次增加的进度值，确保3秒内匀速达到99%
    // 3秒 = 3000毫秒，每50毫秒更新一次，总共需要60次更新
    // 总进度是99，所以每次增加 99/60 ≈ 1.65
    const totalSteps = 60; // 3000ms / 50ms = 60次更新
    const incrementValue = 99 / totalSteps; // 每次增加的值
    
    // 初始化计数器
    let step = 0;
    
    let pollingInterval: NodeJS.Timeout;
    pollingInterval = setInterval(() => {
      step++;
      if (step <= totalSteps) {
        // 根据当前步骤计算应该达到的进度值
        const targetProgress = Math.floor(incrementValue * step);
        setProgress(targetProgress);
      }
      
      // 当达到最后一步或超过时，确保进度为99%并清除定时器
      if (step >= totalSteps) {
        clearInterval(pollingInterval);
        setProgress(99);
      }
    }, 50); // 每50毫秒更新一次

    return () => {
      clearInterval(pollingInterval);
    };
  };

  useEffect(() => {
    // 重置状态
    setProgress(0);
    onSearchCompleted(false, null);

    const cleanup = incrementProgress();

    return () => {
      cleanup();
      setIsPolling(false);
    };
  }, [projectId]); // 移除了progress依赖项

  // 当项目数据更新时检查是否完成
  useEffect(() => {
    if (!isPolling || error) return;
console.log("🚀 ~ file: progress-bar.tsx:75 ~ ----projectData:", projectData)
    if (projectData?.data?.matching_rules && projectData?.data?.search_keywords) {
      // 数据准备好，完成搜索
      console.log("🚀 ~ file: progress-bar.tsx:75 ~ 数据准备好，完成搜索:")
      setProgress(100);
      onSearchCompleted(true, projectData.data);
      setIsPolling(false);
    }
  }, [projectData?.data, isPolling]);

  return (
    <div className="space-y-3 py-2">
      {/* 自定义进度条 */}
      <div className="h-2 w-full bg-gray-200 rounded-full overflow-hidden">
        <div className={cn(
          'h-full bg-blue-500 rounded-full transition-all duration-200',
          progress === 100 && 'bg-green-500'
        )} style={{ width: `${progress}%` }} />
      </div>
      <div className="flex items-center justify-between text-sm">
        <div className="flex items-center gap-2">
          <Loader2 className="h-4 w-4 animate-spin" />
          {title}
        </div>
        <div className="text-muted-foreground">
          {Math.floor(progress)}%
        </div>
      </div>
    </div>
  );
}
